import re
from django.contrib.auth.backends import ModelBackend

from apps.users.models import User

# 抽取代码  作用减少代码的耦合度  代码的复用
from meiduo_mall import settings


def get_user_by_username(username):
    try:
        if re.match(r'^1[3-9]\d{9}$', username):
            # 手机号
            user = User.objects.get(mobile=username)
        else:
            # 用户名
            user = User.objects.get(username=username)
    except User.DoesNotExist:
        return None
    return user

class UsernameMobileModelBackend(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):
        # try:
        #     if re.match(r'^1[3-9]\d{9}$',username):
        #         user = User.objects.get(mobile=username)
        #     else:
        #         user = User.objects.get(username=username)
        # except User.DoesNotExist:
        #     return None
        user = get_user_by_username(username)
        # 根据用户信息验证密码
        if user is not None and user.check_password(password):
            return user


from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

def generic_verify_email_url(user_id):
    s = Serializer(secret_key=settings.SECRET_KEY,expires_in=3600)
    data = {
        'user_id': user_id
    }
    token = s.dumps(data)

    return  settings.EMAIL_VERIFY_URL + '?token=' + token.decode()


def check_verify_email_token(token):
    s = Serializer(secret_key=settings.SECRET_KEY,expires_in=3600*24)
    try:
        result = s.loads(token)
    except User.DoesNotExist:
        return None

    return result.get('user_id')